package enterprise

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"insighttracking/apps/admin/auth"
	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"insighttracking/query/service"
	"net/http"
	"os"
)

type CreateEnterpriseApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewCreateEnterpriseApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *CreateEnterpriseApiLogic {
	hostname, _ := os.Hostname()
	return &CreateEnterpriseApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *CreateEnterpriseApiLogic) CreateEnterpriseApi(req *types.CreateEnterpriseReq) (resp string, err error) {
	// 1.创建企业
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return "", err
	}
	if !k.IsContains([]int64{enum.SuperAdministratorEnum, enum.PlatEnum}, accountInfo.AccountType) {
		return "", errors.New("当前账号没权限创建企业")
	}
	_, err = service.EnterpriseService.GetByName(l.ctx, req.Name)
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return "", errors.New("名称已经存在")
	}
	var fillAddress = ""
	if req.TownCode != "" {
		fillAddress, _ = service.AreaService.GetAreaNameApi(l.ctx, req.TownCode)
	} else {
		fillAddress, _ = service.AreaService.GetAreaNameApi(l.ctx, req.CountyCode)
	}
	tx := dao.Use(l.svcCtx.MysqlDb).Begin()

	enterpriseData := model.EnterpriseEntity{
		Name:         req.Name,                                        // 企业名称
		Person:       req.Person,                                      // 负责人
		Mobile:       req.Mobile,                                      // 联系电话
		Logo:         req.Logo,                                        // 企业logo
		Status:       req.Status,                                      // 状态0：营业  1：停业
		ProvinceCode: req.ProvinceCode,                                // 省份id
		CityCode:     req.CityCode,                                    // 城市id
		CountyCode:   req.CountyCode,                                  // 县、区id
		TownCode:     req.TownCode,                                    // 乡镇code
		Address:      req.Address,                                     // 具体地址
		FullAddress:  fmt.Sprintf("%s/%s,", fillAddress, req.Address), // 拼接省市县地址
	}
	if err = service.EnterpriseService.CreateApi(l.ctx, tx, &enterpriseData); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", err
	}
	// 2.创建企业员工
	personEntity := model.EnterprisePersonEntity{
		EnterpriseID: enterpriseData.ID, // 关联到enterprise表主键id
		Name:         req.Name,          // 员工姓名
		Mobile:       req.Mobile,        // 员工手机号码
	}
	if err = service.EnterprisePersonService.CreateApi(l.ctx, tx, &personEntity); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("创建失败")
	}
	// 2.创建账号
	if err = service.AccountService.CreateApi(l.ctx, tx, &model.AccountEntity{
		Username:     req.Username,        // 用户名
		Password:     req.Password,        // 密码
		ParentID:     0,                   // 父节点id
		AccountType:  enum.EnterpriseEnum, // 账号类型,0表示超管,1表示后台运营人员,2表示企业账号,3表示门店账号，4表示企业内部员工
		EnterpriseID: enterpriseData.ID,   // 企业id,enterprise表主键id
		PersonID:     personEntity.ID,     // 员工id
	}); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", err
	}
	// 创建角色
	var roleData = make([]*model.RoleEntity, 0)
	roleEntities, err := service.RoleService.GetRoleListApi(l.ctx, 1)
	if err == nil && len(roleEntities) > 0 {
		for _, item := range roleEntities {
			roleData = append(roleData, &model.RoleEntity{
				EnterpriseID: enterpriseData.ID, // 关联到enterprise表主键id
				Name:         item.Name,         // 角色名称
				Describe:     item.Describe,     // 角色描述
				RoleCode:     item.RoleCode,     // 角色code
			})
		}
	}
	if err = service.RoleService.CreateBatchApi(l.ctx, tx, roleData); err != nil {
		if err = tx.Rollback(); err != nil {
			return "", err
		}
		return "", errors.New("创建失败")
	}
	if err = tx.Commit(); err != nil {
		return "", errors.New("创建失败")
	}
	return "创建成功", nil
}
